/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.swotxu.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.swotxu.common.exception.BizCodeEnum;
import org.apache.http.HttpStatus;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	private static final String KEY_CODE = "code";
	private static final String KEY_MSG = "msg";
	private static final String KEY_DATA = "data";

	public R() {
		put(KEY_CODE, 0);
		put(KEY_MSG, "success");
	}
	
	public static R error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static R error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}

	public static R error(BizCodeEnum bizCodeEnum) {
		return error(bizCodeEnum.getCode(), bizCodeEnum.getMessage());
	}
	public static R error(int code, String msg) {
		R r = new R();
		r.put(KEY_CODE, code);
		r.put(KEY_MSG, msg);
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put(KEY_MSG, msg);
		return r;
	}
	
	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public int getCode() {
		return (int) this.get(KEY_CODE);
	}

	public boolean isOk() {
		return getCode() == 0;
	}

	public String getMessage() {
		return (String) this.get(KEY_MSG);
	}


	// ------------- 利用fastjson进行逆转 -------------
	public <T> T getValue(String key, TypeReference<T> typeReference) {
		Object data = get(key);//默认是map
		String s = JSON.toJSONString(data);
		return JSON.parseObject(s, typeReference);
	}

	/**
	 * 获取 data 时，从 ValueHolder 中获取。
	 * 单类型，传递 Class / Type
	 * @param type
	 * @param <T>
	 * @return
	 */
	public <T> T getData(Type type) {
		return getValue(KEY_DATA, new TypeReference<ValueHolder<T>>(type) {}).value;
	}

	/**
	 * 获取 data 时，从 ValueHolder 中获取。
	 * 多嵌套类型，传递 typeReference，
	 * @param typeReference
	 * @param <T>
	 * @return
	 */
	public <T> T getData(TypeReference<T> typeReference) {
		return getData(typeReference.getType());
	}

	// 设置 data 时，封装到 ValueHolder
	public <T> R setData(T data){
		put(KEY_DATA,new ValueHolder<T>(data));
		return this;
	}

	/**
	 * 参数持有者
	 * @param <T>
	 */
	public static class ValueHolder<T> {
		public T value;

		public ValueHolder() {}

		public ValueHolder(T value) {
			this.value = value;
		}

//		public T getValue() {
//			return value;
//		}
//
//		public void setValue(T value) {
//			this.value = value;
//		}
	}
}
